#-*- encoding:utf-8 -*-
import web
from datetime import datetime
from configs import access_control
from components import forms
from components import pagination
from components.utils import md5
from components.render import view, view_plain
from models import postModel, settingModel

class PostList(object):
	def __init__(self, status, pager_url, fields='*',perpage=None, **conditions):
		self.status = status
		self.pager_url = pager_url
		self.fields = fields
		self.conditions = conditions
		self.conditions['status'] = status
		self.current_page = 0;
		if not perpage:
			perpage = int(settingModel.getConfig('pagination', 10))
		self.perpage = perpage

	def posts(self):
		self.current_page = int(web.input().get('page',1))
		if self.current_page < 1 :
			self.current_page = 1
		offset = (self.current_page - 1) * self.perpage

		return postModel.findAll(self.conditions, self.fields, self.perpage, offset)

	def pager(self):
		total = postModel.findCount(self.conditions)
		return pagination.pager({
			'perpage' : self.perpage,
			'total': total,
			'current_page' : self.current_page,
			'url' : self.pager_url
		})

class controller(object):
	def __init__(self):
		cls = self.__class__.__name__

		session = web.config.get('_session')
		self.loggedin = session.get('loggedin')

		if cls in access_control:
			if not self.loggedin:
				raise web.seeother('/login')

class latest(controller):
	def GET(self):
		posts = postModel.latest()
		return view.posts.latest(posts)

class posts(controller):
	def GET(self):
		postList = PostList('published', 'posts', 'id,title,created')
		posts = postList.posts()
		pager = postList.pager()
		return view.posts.list(posts, pager)

class published(controller):
	def GET(self):
		postList = PostList('published', 'published',  'id,title,created', 15)
		posts = postList.posts()
		pager = postList.pager()
		return view.posts.published(posts, pager)

class draft(controller):
	def GET(self):
		postList = PostList('draft', 'draft', 'id,title,created', 15)
		posts = postList.posts()
		pager = postList.pager()
		return view.posts.draft(posts, pager)

class post(controller):
	def GET(self,id):
		record = postModel.findById(id)
		if record:
			if record.status != 'draft' or self.loggedin:
				return view.posts.post(record)
		raise web.seeother('/notfound')

class add(controller):
	def GET(self):
		form = forms.post_form()
		return view.posts.add(form)

	def POST(self):
		form = forms.post_form()
		if form.validates():
			ret = postModel.add(form.d)
			if ret[0] :
				raise web.seeother('/'+form.d.get('status'))
			else :
				form.post = ret[1]		
				return view.posts.add(form)	
		else :
			return view.posts.add(form)

class edit(controller):
	def GET(self,id):
		record = postModel.findById(id)
		if record:
			form = forms.post_form(record)
			return view.posts.edit(form)
		raise web.seeother('/settings')

	def POST(self,id=None):
		form = forms.post_form()
		if form.validates():
			ret = postModel.update(form.d)
			if ret[0] :
				raise web.seeother('/'+form.d.get('status'))
			else :
				form.post = ret[1]		
				return view.posts.edit(form,False)	
		else :
			return view.posts.edit(form,False)

class delete(controller):
	def GET(self,id):
		postModel.delete(id)
		raise web.seeother('/published')

	def POST(self,id):
		postModel.delete(id)
		raise web.seeother('/published')

class about(controller):
	def GET(self):
		config = settingModel.find(dict(name='about'))
		data = None
		if config:
			data = config.value
		return view.site.about(data)

class settings(controller):
	def GET(self):
		configs = settingModel.findAll()
		data = {}
		if len(configs):
			data = {item['name'] : item['value'] for item in configs}
		form = forms.settings_form(data)
		return view.site.settings(form)
	def POST(self):
		form = forms.settings_form()
		if form.validates():
			ret = settingModel.save(form.d)
			if ret[0] :
				raise web.seeother('/settings')
			else :
				form.post = ret[1]		
				return view.site.settings(form,False)	
		else :
			return view.site.settings(form)

class login(object):
	def GET(self):
		session = web.config.get('_session')
		if session.get('loggedin'):
			raise web.seeother('/settings')

		next = web.ctx.env.get('HTTP_REFERER','/settings')
		return view.site.auth(next,False)
	def POST(self):
		password = web.input().get('password')
		next = web.input().get('next','/settings')

		if settingModel.auth(password):
			session = web.config.get('_session')
			session.loggedin = True
			raise web.seeother(next)
		else:
			return view.site.auth(next,True)

class logout(object):
	def GET(self):
		session = web.config.get('_session')
		session.loggedin = False
		raise web.seeother('/')

class feed(object):
	def GET(self):
		date = datetime.today().strftime("%a, %d %b %Y %H:%M:%S +0800")
		posts = postModel.latest('id,title,created,content',10)
		web.header('Content-Type', 'application/xml')
		return view_plain.site.feed(posts,date)

class upload(controller):
    def POST(self):
        data = web.input(uploader={})
        filedir = 'static/uploads'
        if 'uploader' in data: 
            filepath = data.uploader.filename.replace('\\','/') 
            filename = filepath.split('/')[-1] 
            name,extension = filename.split('.')
            
            filename = md5(datetime.now().strftime("%Y-%m-%d %H:%m:%S"))
            filename = filename + '.' + extension.lower()
            file_full_path = filedir +'/'+ filename

            fout = open(file_full_path,'w') 
            fout.write(data.uploader.file.read()) 
            fout.close()
            return '/' + file_full_path
        return ''

class notfound(controller):
	def GET(self):
		return view.error.notfound()

class internalerror(controller):
	def GET(self):
		return view.error.internalerror()
